#include <string.h>
#include <burst_kernel.h>
#include <burst_module.h>

static struct rb_root bus_module_tree = {0};

static int valuecmp(int val1, int val2)
{
	return val1 - val2;
}

static int __bus_module_insert(struct rb_root *root, bus_module_t *data)
{
	struct rb_node **n = &(root->rb_node), *parent = NULL;

	if(!data)
		return 0;
	/* Figure out where to put n node */
	while (*n) {
		bus_module_t *t = (bus_module_t *)container_of(*n, bus_module_t, node);
		int result = strcmp(data->info->name, t->info->name);

		parent = *n;
		if (result < 0)
			n = &((*n)->rb_left);
		else if (result > 0)
			n = &((*n)->rb_right);
		else
			return 0;
	}

	/* Add n node and rebalance tree. */
	rb_link_node(&data->node, parent, n);
	rb_insert_color(&data->node, root);

	return TRUE;
}

static bus_module_t *__bus_module_search(struct rb_root *root, char *name)
{
	struct rb_node *nodes = root->rb_node;
	bus_module_t *data = (bus_module_t *)container_of(root->rb_node, bus_module_t, node);
	int result;
	while (nodes) {
		data = (bus_module_t *)container_of(nodes, bus_module_t, node);

		result = strcmp(name, data->info->name);

		if (result < 0) 
			nodes = nodes->rb_left;
		else if (result > 0)
			nodes = nodes->rb_right;
		else 
			return data;
	}
	return 0;
}

static void __bus_module_erase(struct rb_root *root, char *name)
{
	bus_module_t *ck = __bus_module_search(root, name);
	if(!ck)
		return;
	rb_erase(&ck->node, (struct rb_root *)root);
	return;
}

int bus_module_insert(bus_module_t *data)
{
	return __bus_module_insert(&bus_module_tree, data);
}

bus_module_t *bus_module_search(char *name)
{
	return __bus_module_search(&bus_module_tree, name);
}

void bus_module_erase(char *name)
{
	__bus_module_erase(&bus_module_tree, name);
}